//
//  CNUITextField.swift
//  Voice
//
//  Created by 卢逢卫 on 2024/3/5.
//

import UIKit
public class CNUITextField: UITextField {

    /// 结束输入的回调
    public var endInputBlock: ((String) -> ())?

    /// 输入的内容类型，默认是 normal
    public var inputType: CNUITextFieldInputType

    public convenience init(text: String, textColor: UIColor, textFont: UIFont, placeholderText: String?, placeholderColor: UIColor?, placeholderFont: UIFont?, cursorColor: UIColor?, textContentType: UITextContentType?, keyboardType: UIKeyboardType, returnKeyType: UIReturnKeyType, alignment: NSTextAlignment) {
        self.init(frame: .zero)
        self.text = text
        self.textColor = textColor
        self.font = textFont
        self.placeholder = placeholderText
//        self.placeholderColor = placeholderColor
//        self.placeholderFont = placeholderFont
        self.tintColor = cursorColor
        self.textContentType = textContentType
        self.keyboardType = keyboardType
        self.returnKeyType = returnKeyType
        self.textAlignment = alignment
        
        if let placeholderText = placeholderText, let placeholderColor = placeholderColor, let placeholderFont = placeholderFont {
                let attributes: [NSAttributedString.Key: Any] = [
                    .foregroundColor: placeholderColor,
                    .font: placeholderFont
                ]
                self.attributedPlaceholder = NSAttributedString(string: placeholderText, attributes: attributes)
        }
        
    }

    override public init(frame: CGRect) {
        self.inputType = .normal
        super.init(frame: frame)
        self.delegate = self
    }

    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension CNUITextField: UITextFieldDelegate {

    public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }

    public func textFieldDidEndEditing(_ textField: UITextField) {
        if let text = textField.text {
            endInputBlock?(text)
        }
    }

    public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        guard let currentText = textField.text else { return true }
        let newText = (currentText as NSString).replacingCharacters(in: range, with: string)
        
        // 根据输入类型进行限制或处理
        
        return true
    }
}

/// CNUITextFieldInputType
///
/// : number、normal、money、money_leftView、phone
///
public enum CNUITextFieldInputType {
    case number
    case normal
    case money
    case money_leftView
    case phone
}

extension UITextField {
    func cn_setLeftViewIcon(image: UIImage, padding: CGFloat) {
        let imageView = UIImageView(image: image)
        imageView.contentMode = .scaleAspectFit
        imageView.frame = CGRect(x: 0, y: 0, width: image.size.width + padding, height: image.size.height)
        
        let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: image.size.width + padding, height: image.size.height))
        paddingView.addSubview(imageView)
        
        leftView = paddingView
        leftViewMode = .always
    }
    
    func cn_setRightViewIcon(image: UIImage, padding: CGFloat) {
            let imageView = UIImageView(image: image)
            imageView.contentMode = .center
            let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: image.size.width + padding, height: image.size.height))
            paddingView.addSubview(imageView)
            paddingView.contentMode = .center
            self.rightView = paddingView
            self.rightViewMode = .always
        }
}



extension UITextField {
    func cn_setPlaceholderColor(color: UIColor) {
        guard let placeholder = self.placeholder else {
            return
        }
        
        let attributes = [NSAttributedString.Key.foregroundColor: color]
        self.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: attributes)
    }
}

extension UITextField {
    var cn_maxLength: Int {
        get {
            if let maxLength = objc_getAssociatedObject(self, &AssociatedKeys.cn_maxLength) as? Int {
                return maxLength
            }
            return Int.max
        }
        set {
            objc_setAssociatedObject(self, &AssociatedKeys.cn_maxLength, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            self.addTarget(self, action: #selector(cn_checkMaxLength), for: .editingChanged)
        }
    }
    
    @objc private func cn_checkMaxLength() {
        guard let text = self.text, text.count > cn_maxLength else {
            return
        }
        
        let endIndex = text.index(text.startIndex, offsetBy: cn_maxLength)
        self.text = String(text[text.startIndex..<endIndex])
    }
}

private struct AssociatedKeys {
    static var cn_maxLength = "cn_maxLength"
}
